package com.crm.report.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.crm.custinfo.service.impl.UserInfoComm;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.crm.report.domain.UserBusinessGoal;
import com.crm.report.service.IUserBusinessGoalService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 周目标管理Controller
 * 
 * @author ruoyi
 * @date 2024-02-29
 */
@RestController
@RequestMapping("/crmsys/userGoal")
public class UserBusinessGoalController extends BaseController
{
    @Autowired
    private IUserBusinessGoalService userBusinessGoalService;
    @Autowired
    private UserInfoComm userInfoComm;

    /**
     * 查询周目标管理列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:list')")
    @GetMapping("/list")
    public AjaxResult list(UserBusinessGoal userBusinessGoal)
    {
        Map<String,Object> result = new HashMap<String,Object>();
        Map<String,Object> inParams = userBusinessGoal.getParams();
        int right_type = userInfoComm.getRightType();
        if (right_type == 4){
            //业务员只能看自己的数据
            userBusinessGoal.setEmpId(getUserId());
        }
        result.put("rightType", right_type);
        if(userBusinessGoal.getGoalDate()==null||userBusinessGoal.getGoalDate().isEmpty()) {
            result.put("list", new ArrayList<>());
            return AjaxResult.success(result);
        }
        //获取周日和周六
        List<String> dateList= DateUtils.getSundayAndSaturday(DateUtils.parseDate(userBusinessGoal.getGoalDate()));

        inParams.put("startGoalDate", dateList.get(0));
        inParams.put("endGoalDate", dateList.get(1));

        String queryType= MapUtils.getString(inParams,"queryType");

        Long deptId= userBusinessGoal.getOrgId()==null?getDeptId():userBusinessGoal.getOrgId();
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);

        inParams.put("deptIds",orgIds);

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        if ("6".equals(queryType)) {// 6.个人业绩排行
            list = userBusinessGoalService.queryUserGoalList(userBusinessGoal);
        } else if ("4".equals(queryType)) { // 3.二级部门
            inParams.put("dept", "1");
            userBusinessGoal.setParams(inParams);
            list = userBusinessGoalService.queryDeptGoalList(userBusinessGoal);
        } else if ("3".equals(queryType)) { // 2.一级部门
            inParams.put("area", "1");
            userBusinessGoal.setParams(inParams);
            list = userBusinessGoalService.queryAreaGoalList(userBusinessGoal);
        } else if ("2".equals(queryType)) { // 1.分公司
            list = userBusinessGoalService.queryCompanyGoalList(userBusinessGoal);
        }
        result.put("list", list);
        return AjaxResult.success(result);
    }



    /**
     * 指标排行
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:indicatorRankingV2:list')")
    @GetMapping("/indicatorRankingV2/list")
    public AjaxResult indicatorRankingV2(UserBusinessGoal userBusinessGoal) {
        Map<String,Object> resMap = new HashMap<String, Object>();
        Map<String,Object> inParams = userBusinessGoal.getParams();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        int right_type = userInfoComm.getRightType();
        resMap.put("rightType", right_type);
        // 查询整个城市的排行
        Long deptId= userBusinessGoal.getOrgId()==null?getDeptId():userBusinessGoal.getOrgId();
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);


        String queryType= MapUtils.getString(inParams,"queryType");

        inParams.put("deptIds",orgIds);
        if ("6".equals(queryType)) {// 6.个人排行
            list = userBusinessGoalService.indicatorRankingPersonal(userBusinessGoal);
        } else if ("4".equals(queryType)) { // 3.二级部门
            inParams.put("dept", "1");
            userBusinessGoal.setParams(inParams);
            list = userBusinessGoalService.indicatorRankingDept2(userBusinessGoal);
        } else if ("3".equals(queryType)) { // 2.一级部门
            inParams.put("area", "1");
            userBusinessGoal.setParams(inParams);
            list = userBusinessGoalService.indicatorRankingDept1(userBusinessGoal);
        } else if ("2".equals(queryType)) { // 1.分公司
            list = userBusinessGoalService.indicatorRankingSubOrg(userBusinessGoal);
        }

        resMap.put("list", list);
        return AjaxResult.success(resMap);
    }

    /**
     * 部长指标排行
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userIndicatorRanking:list')")
    @GetMapping("/userIndicatorRanking/list")
    public AjaxResult userIndicatorRanking(UserBusinessGoal userBusinessGoal) {
        Map<String,Object> resMap = new HashMap<String, Object>();
        Map<String,Object> inParams = userBusinessGoal.getParams();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        // 查询整个城市的排行
        Long deptId= userBusinessGoal.getOrgId()==null?getDeptId():userBusinessGoal.getOrgId();
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);

        inParams.put("deptIds",orgIds);

        userBusinessGoal.setParams(inParams);
        list = userBusinessGoalService.userIndicatorRanking(userBusinessGoal);

        resMap.put("list", list);
        return AjaxResult.success(resMap);
    }



    /**
     * 导出周目标管理列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:export')")
    @Log(title = "周目标管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserBusinessGoal userBusinessGoal)
    {
        List<UserBusinessGoal> list = userBusinessGoalService.selectUserBusinessGoalList(userBusinessGoal);
        ExcelUtil<UserBusinessGoal> util = new ExcelUtil<UserBusinessGoal>(UserBusinessGoal.class);
        util.exportExcel(response, list, "周目标管理数据");
    }

    /**
     * 获取周目标管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userBusinessGoalService.selectUserBusinessGoalById(id));
    }

    /**
     * 新增周目标管理
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:add')")
    @Log(title = "周目标管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserBusinessGoal userBusinessGoal)
    {

        if (DateUtils.isThisWeek( userBusinessGoal.getGoalDate())) {
            return AjaxResult.warn(String.format("日期[%s]，周目标不允许提前录入", userBusinessGoal.getGoalDate()));
        }



        UserBusinessGoal businessGoal = new UserBusinessGoal();
        businessGoal.setGoalDate(userBusinessGoal.getGoalDate());
        businessGoal.setEmpId(getUserId());
        List<UserBusinessGoal> userBusinessGoalList=userBusinessGoalService.selectUserBusinessGoalList(businessGoal);
        if(!userBusinessGoalList.isEmpty()){
            return AjaxResult.warn(String.format("日期[%s]的周目标已经录入过了", userBusinessGoal.getGoalDate()));
        }
        java.util.Date curDate = new Date();
        if (userBusinessGoal.getId() == null || userBusinessGoal.getId() <= 0) {
            userBusinessGoal.setCreateTime(curDate);
            userBusinessGoal.setEmpId(getUserId());
            userBusinessGoal.setOrgId(getDeptId());
        }

        return toAjax(userBusinessGoalService.insertUserBusinessGoal(userBusinessGoal));
    }

    /**
     * 修改周目标管理
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:edit')")
    @Log(title = "周目标管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserBusinessGoal userBusinessGoal)
    {
        java.util.Date curDate = new Date();
        userBusinessGoal.setUpdateTime(curDate);
        return toAjax(userBusinessGoalService.updateUserBusinessGoal(userBusinessGoal));
    }

    /**
     * 删除周目标管理
     */
    @PreAuthorize("@ss.hasPermi('crmsys:userGoal:remove')")
    @Log(title = "周目标管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userBusinessGoalService.deleteUserBusinessGoalByIds(ids));
    }


}
